import React from 'react';
import {View, Text, FlatList} from 'react-native';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import _ from 'lodash';
import Styles from './styles';
import ThemeStyles from '../../styles';
import Search from '../../components/search';
import Drawer from 'react-native-drawer';
import FilterPanel from './filter-panel';
import IconFont from '../../resource/iconfont';
import {getRealSize, Touchable} from '../../utils';
import * as filterActionCreator from '../../actions/filter-actions';
import * as searchActionCreator from '../../actions/search-actions';
import {FixedParams} from '../../reducers/constant';
import Tag from '../../components/tag';
import Rate from '../../components/rate';
import {connectActionSheet} from '@expo/react-native-action-sheet';
import {LoadingStatus} from '../../reducers/app-state';
import FastImage from 'react-native-fast-image';
import {I18n} from '../../reducers/intl';
import LogoSvg from '../../resource/svg/logo.svg';
import Svg, {Image, SvgCss, SvgUri, SvgXml} from 'react-native-svg';

class SearchScreen extends React.PureComponent {
  static navigationOptions = {
    header: null,
  };

  constructor(props) {
    super(props);
    this.state = {
      allowSubmit: true,
      errors: [],
      drawer: false,
    };
  }

  componentDidMount() {
    const {searchActions, filterParams} = this.props;
    searchActions.search(filterParams);
    // navigation.addListener('willFocus', () =>
    //   searchActions.search(filterParams),
    // );
  }

  onChangeValue = async (field, value) => {
    const {filterActions} = this.props;
    filterActions.update({[field]: value});
    // searchActions.search(filterParams);
  };

  onSelectedItem = (field, value) => {
    const {filterActions, filterParams} = this.props;
    if (field === 'avail') {
      filterActions.update({avail: value});
    } else if (field === 'type') {
      if (filterParams.type !== value) {
        filterActions.update({type: value});
      }
    } else if (field === 'product') {
      this.onReset();
      if (filterParams.product) {
        if (filterParams.product !== value) {
          filterActions.update({product: value});
        }
      } else {
        filterActions.update({product: value});
      }
    } else if (FixedParams.materials === field) {
      filterActions.update({
        [FixedParams.materials]: [value],
        [FixedParams.metal_types]: [],
      });
    } else if (FixedParams.metal_types === field) {
      filterActions.update({[FixedParams.metal_types]: [value]});
    } else {
      const values = filterParams[field];
      if (_.includes(values, value)) {
        _.remove(filterParams[field], v => v === value);
        filterActions.update({[field]: values});
      } else {
        if (values) {
          values.push(value);
          filterActions.update({[field]: values});
        } else {
          filterActions.update({[field]: [value]});
        }
      }
    }
  };

  onSelectedMenuItem = (field, value) => {
    const {filterActions, searchActions, filterParams} = this.props;
    filterActions.update({[field]: value});
    searchActions.search(filterParams.ordering);
  };

  onReset = () => {
    const {filterActions} = this.props;
    filterActions.reset();
  };

  onChangeOrder = () => {
    const {filterActions, searchActions, filterParams, orderOptions} =
      this.props;
    this.props.showActionSheetWithOptions(
      {
        options: orderOptions.map(option => option.label),
        cancelButtonIndex: 3,
        destructiveButtonIndex: 3,
        textStyle: {flex: 1},
      },
      buttonIndex => {
        let ordering = '';
        if (buttonIndex === 3) {
          return;
        }
        if (buttonIndex) {
          ordering = orderOptions[buttonIndex].value;
        }
        filterActions.update({ordering});
        searchActions.search({...filterParams, ordering});
      },
    );
  };

  render() {
    const {
      filterParams,
      categories,
      navigation,
      data,
      searchActions,
      filterActions,
      appState,
      currentPage,
      orderOptions,
    } = this.props;
    const list = Object.values(data);
    // const temp = list.map(o => ({i: o.index, name: o.vendor_name}));
    const orderList = _.orderBy(list, 'index', 'asc');
    // const names = orderList.map(r => r.vendor_name);
    // console.log(temp);
    const option = orderOptions.find(o => o.value === filterParams.ordering);
    return (
      <Drawer
        ref={ref => (this._drawer = ref)}
        content={
          <FilterPanel
            products={categories}
            values={filterParams}
            onSelected={this.onSelectedItem}
            onReset={() => filterActions.reset()}
            onApply={() => {
              this.setState({drawer: false});
              searchActions.search(filterParams);
            }}
            onClose={() => this.setState({drawer: false})}
          />
        }
        onClose={() => this.setState({drawer: false})}
        open={this.state.drawer}
        type="displace"
        tapToClose
        openDrawerOffset={0.2}
        panCloseMask={0.2}
        side="right">
        <View style={Styles.container}>
          <View style={Styles.search}>
            <Search
              value={filterParams.keywords}
              placeholder={I18n.t('form.placeholder.search')}
              onChange={value => this.onChangeValue('keywords', value)}
              onSearch={() => searchActions.search(filterParams)}
            />
          </View>
          <View style={Styles.title}>
            <Touchable onPress={this.onChangeOrder}>
              <View>
                <Text
                  style={[
                    ThemeStyles.Front.title.smallReg,
                    ThemeStyles.Color.text.tintGray,
                  ]}>
                  {option ? option.label : I18n.t('options.sort.default')}
                </Text>
              </View>
            </Touchable>
            <View style={Styles.filterAction}>
              <Touchable
                onPress={() => {
                  this.setState({drawer: true});
                }}>
                <View
                  style={[
                    ThemeStyles.Layout.flex.row,
                    ThemeStyles.Layout.flex.horizontalCenter,
                    {paddingHorizontal: 4},
                  ]}>
                  <Text
                    style={[
                      ThemeStyles.Front.title.smallReg,
                      ThemeStyles.Color.text.tintGray,
                    ]}>
                    {I18n.t('form.label.filter')}
                  </Text>
                  <IconFont
                    name="molarshaixuan"
                    color="#979797"
                    size={getRealSize(18)}
                  />
                </View>
              </Touchable>
              <View style={[ThemeStyles.divider.vertical]} />
              <Touchable onPress={() => navigation.navigate('SupplierMap')}>
                <IconFont
                  style={{marginHorizontal: getRealSize(8)}}
                  name="molarditu"
                  color="#979797"
                  size={getRealSize(18)}
                />
              </Touchable>
            </View>
          </View>
          <View style={[ThemeStyles.divider.horizontal]} />
          <FlatList
            data={orderList}
            onRefresh={() => searchActions.search(filterParams)}
            refreshing={appState.loading === LoadingStatus.PENDING}
            onEndReached={() =>
              searchActions.search(filterParams, currentPage + 1)
            }
            onEndReachedThreshold={0.1}
            keyExtractor={item => `${item.id}`}
            renderItem={({item}) => (
              <SupplierCard
                {...item}
                onPress={() =>
                  navigation.navigate('Supplier', {supplierId: item.id})
                }
              />
            )}
          />
        </View>
      </Drawer>
    );
  }
}

const SupplierCard = props => (
  <Touchable onPress={() => props.onPress()}>
    <View style={Styles.supplierCardContainer}>
      <View style={Styles.supplierCardContent}>
        <Text style={Styles.supplierCardTitle}>{props.vendor_name}</Text>
        <View style={Styles.supplierCardExtra}>
          <Rate score={Number(props.rate || 0)} readOnly size={18} />
          {false && (
            <Tag
              styles={{marginLeft: getRealSize(4)}}
              label="曾下过单"
              color="#ED7D4F"
            />
          )}
          {props.weight > 1 && (
            <Tag label="ad" styles={{marginLeft: getRealSize(4)}} />
          )}
        </View>
        <Text style={Styles.supplierCardDesc}>
          {`${props.country || ''}${props.province || ''}${props.city || ''}${
            props.address_1 || ''
          }`}
        </Text>
      </View>
      <View style={Styles.supplierCardImage}>
        <FastImage
          style={{width: getRealSize(48), height: getRealSize(48)}}
          source={{
            priority: FastImage.priority.normal,
            uri: _.get(props, 'avatar.url'),
          }}
        />
      </View>
    </View>
  </Touchable>
);

const mapStateToProps = state => ({
  appState: state.appState,
  filterParams: state.filterParams,
  data: state.searchResultList.results,
  currentPage: state.searchResultList.current,
  user: state.user,
  categories: state.constant.category,
  orderOptions: [
    {label: I18n.t('options.sort.default'), value: ''},
    {label: I18n.t('options.sort.orders'), value: 'orders__count'},
    {label: I18n.t('options.sort.rate'), value: 'rate'},
    {label: I18n.t('button.close'), value: ''},
  ],
});

const mapDispatchToProps = dispatch => ({
  filterActions: bindActionCreators(filterActionCreator, dispatch),
  searchActions: bindActionCreators(searchActionCreator, dispatch),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(connectActionSheet(SearchScreen));
